package opensearchext

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"
	"strings"
	"time"

	opensearchapi "github.com/opensearch-project/opensearch-go/opensearchapi"
)

// ----- API Definition -------------------------------------------------------

// CreateRole removes a document from the index.
type CreateRole func(index string, id string, o ...func(*CreateRoleRequest)) (*opensearchapi.Response, error)

// CreateRoleRequest configures the CreateRole API request.
type IndexPermission struct {
	IndexPatterns  []string `json:"index_patterns,omitempty"`
	Dls            string   `json:"dls,omitempty"`
	Fls            []string `json:"fls,omitempty"`
	MaskedFields   []string `json:"masked_fields,omitempty"`
	AllowedActions []string `json:"allowed_actions,omitempty"`
}
type TenantPermission struct {
	TenantPatterns []string `json:"tenant_patterns,omitempty"`
	AllowedActions []string `json:"allowed_actions,omitempty"`
}
type CreateRoleRequest struct {
	RoleName           string             `json:"role_name,omitempty"`
	ClusterPermissions []string           `json:"cluster_permissions,omitempty"`
	IndexPermissions   []IndexPermission  `json:"index_permissions,omitempty"`
	TenantPermissions  []TenantPermission `json:"tenant_permissions,omitempty"`

	IfPrimaryTerm       *int
	IfSeqNo             *int
	Refresh             string
	Routing             string
	Timeout             time.Duration
	Version             *int
	VersionType         string
	WaitForActiveShards string

	Pretty     bool
	Human      bool
	ErrorTrace bool
	FilterPath []string

	Header http.Header

	ctx context.Context
}
type UpdateBody struct {
	IndexPermissions IndexPermission `json:"index_permission,omitempty"`
}

type UpdateRoleRequest struct {
	RoleName string `json:"role_name,omitempty"`
	Body     []UpdateBody
	Header   http.Header

	ctx context.Context
}

func (u UpdateBody) MarshalJSON() ([]byte, error) {
	urMap := make(map[string]interface{})
	if len(u.IndexPermissions.IndexPatterns) > 0 {
		urMap["value"] = u.IndexPermissions
		urMap["op"] = "add"
		urMap["path"] = "/index_permissions/0"
	}

	return json.Marshal(urMap)
}

func (u UpdateRoleRequest) MarshalJSON() ([]byte, error) {

	return json.Marshal(u.Body)
}
func (i IndexPermission) MarshalJSON() ([]byte, error) {
	ipMap := make(map[string]interface{})
	if i.Dls != "" {
		ipMap["dls"] = i.Dls
	}
	if len(i.Fls) > 0 {
		ipMap["fls"] = i.Fls
	}
	if len(i.IndexPatterns) > 0 {
		ipMap["index_patterns"] = i.IndexPatterns
	}
	if len(i.AllowedActions) > 0 {
		ipMap["allowed_actions"] = i.AllowedActions
	}
	if len(i.MaskedFields) > 0 {
		ipMap["masked_fields"] = i.MaskedFields
	}
	return json.Marshal(ipMap)
}

func (t TenantPermission) MarshalJSON() ([]byte, error) {
	tpMap := make(map[string]interface{})
	if len(t.AllowedActions) > 0 {
		tpMap["allowed_actions"] = t.AllowedActions
	}
	if len(t.TenantPatterns) > 0 {
		tpMap["tenant_patterns"] = t.TenantPatterns
	}

	return json.Marshal(tpMap)
}

func (r CreateRoleRequest) MarshalJSON() ([]byte, error) {
	crrMap := make(map[string]interface{})
	if len(r.ClusterPermissions) > 0 {
		crrMap["cluster_permissions"] = r.ClusterPermissions
	}
	if len(r.IndexPermissions) > 0 {
		crrMap["index_permissions"] = r.IndexPermissions
	}
	if len(r.TenantPermissions) > 0 {
		crrMap["tenant_permissions"] = r.TenantPermissions
	}
	return json.Marshal(crrMap)
}

// Do executes the request and returns response or error.
func (r CreateRoleRequest) Do(ctx context.Context, transport opensearchapi.Transport) (*opensearchapi.Response, error) {
	var (
		method string
		path   strings.Builder
		params map[string]string
	)

	method = "PUT"
	//_plugins/_security/api/internalusers/<username>
	path.Grow(1 + len("_plugins") + 1 + len("_security") + 1 + len("api") + 1 + len("roles") + 1 + len(r.RoleName))
	path.WriteString("/_plugins/_security/api/roles/")
	path.WriteString(r.RoleName)

	params = make(map[string]string)

	if r.IfPrimaryTerm != nil {
		params["if_primary_term"] = strconv.FormatInt(int64(*r.IfPrimaryTerm), 10)
	}

	if r.IfSeqNo != nil {
		params["if_seq_no"] = strconv.FormatInt(int64(*r.IfSeqNo), 10)
	}

	if r.Refresh != "" {
		params["refresh"] = r.Refresh
	}

	if r.Routing != "" {
		params["routing"] = r.Routing
	}

	if r.Timeout != 0 {
		params["timeout"] = formatDuration(r.Timeout)
	}

	if r.Version != nil {
		params["version"] = strconv.FormatInt(int64(*r.Version), 10)
	}

	if r.VersionType != "" {
		params["version_type"] = r.VersionType
	}

	if r.WaitForActiveShards != "" {
		params["wait_for_active_shards"] = r.WaitForActiveShards
	}

	if r.Pretty {
		params["pretty"] = "true"
	}

	if r.Human {
		params["human"] = "true"
	}

	if r.ErrorTrace {
		params["error_trace"] = "true"
	}

	if len(r.FilterPath) > 0 {
		params["filter_path"] = strings.Join(r.FilterPath, ",")
	}

	reqBody, err := json.Marshal(r)
	if err != nil {
		return nil, fmt.Errorf("failed to marshal structure: %s", err)
	}
	body := strings.NewReader(string(reqBody))

	req, err := newRequest(method, path.String(), body)
	if err != nil {
		return nil, fmt.Errorf("failed to form request: %s", err)
	}

	if len(params) > 0 {
		q := req.URL.Query()
		for k, v := range params {
			q.Set(k, v)
		}
		req.URL.RawQuery = q.Encode()
	}
	if body != nil {
		req.Header[headerContentType] = []string{headerContentTypeJSON}
	}

	if len(r.Header) > 0 {
		if len(req.Header) == 0 {
			req.Header = r.Header
		} else {
			for k, vv := range r.Header {
				for _, v := range vv {
					req.Header.Add(k, v)
				}
			}
		}
	}

	if ctx != nil {
		req = req.WithContext(ctx)
	}

	res, err := transport.Perform(req)
	if err != nil {
		return nil, fmt.Errorf("failed to perform request: %s", err)
	}

	response := opensearchapi.Response{
		StatusCode: res.StatusCode,
		Body:       res.Body,
		Header:     res.Header,
	}

	return &response, nil
}

func (u UpdateRoleRequest) Do(ctx context.Context, transport opensearchapi.Transport) (*opensearchapi.Response, error) {
	var (
		method string
		path   strings.Builder
	)

	method = "PATCH"
	//_plugins/_security/api/roles/<role>
	path.Grow(len("/_plugins/_security/api/roles") + 1 + len(u.RoleName))
	path.WriteString("/_plugins/_security/api/roles/")
	path.WriteString(u.RoleName)

	reqBody, err := json.Marshal(u)
	if err != nil {
		return nil, err
	}
	body := strings.NewReader(string(reqBody))

	req, err := newRequest(method, path.String(), body)
	if err != nil {
		return nil, err
	}
	if body != nil {
		req.Header[headerContentType] = []string{headerContentTypeJSON}
	}

	if len(u.Header) > 0 {
		if len(req.Header) == 0 {
			req.Header = u.Header
		} else {
			for k, vv := range u.Header {
				for _, v := range vv {
					req.Header.Add(k, v)
				}
			}
		}
	}

	if ctx != nil {
		req = req.WithContext(ctx)
	}

	res, err := transport.Perform(req)
	if err != nil {
		return nil, err
	}

	response := opensearchapi.Response{
		StatusCode: res.StatusCode,
		Body:       res.Body,
		Header:     res.Header,
	}

	return &response, nil
}

// WithContext sets the request context.
func (f CreateRole) WithContext(v context.Context) func(*CreateRoleRequest) {
	return func(r *CreateRoleRequest) {
		r.ctx = v
	}
}

// WithIfPrimaryTerm - only perform the CreateRole operation if the last operation that has changed the document has the specified primary term.
func (f CreateRole) WithIfPrimaryTerm(v int) func(*CreateRoleRequest) {
	return func(r *CreateRoleRequest) {
		r.IfPrimaryTerm = &v
	}
}

// WithIfSeqNo - only perform the CreateRole operation if the last operation that has changed the document has the specified sequence number.
func (f CreateRole) WithIfSeqNo(v int) func(*CreateRoleRequest) {
	return func(r *CreateRoleRequest) {
		r.IfSeqNo = &v
	}
}

// WithRefresh - if `true` then refresh the affected shards to make this operation visible to search, if `wait_for` then wait for a refresh to make this operation visible to search, if `false` (the default) then do nothing with refreshes..
func (f CreateRole) WithRefresh(v string) func(*CreateRoleRequest) {
	return func(r *CreateRoleRequest) {
		r.Refresh = v
	}
}

// WithRouting - specific routing value.
func (f CreateRole) WithRouting(v string) func(*CreateRoleRequest) {
	return func(r *CreateRoleRequest) {
		r.Routing = v
	}
}

// WithTimeout - explicit operation timeout.
func (f CreateRole) WithTimeout(v time.Duration) func(*CreateRoleRequest) {
	return func(r *CreateRoleRequest) {
		r.Timeout = v
	}
}

// WithVersion - explicit version number for concurrency control.
func (f CreateRole) WithVersion(v int) func(*CreateRoleRequest) {
	return func(r *CreateRoleRequest) {
		r.Version = &v
	}
}

// WithVersionType - specific version type.
func (f CreateRole) WithVersionType(v string) func(*CreateRoleRequest) {
	return func(r *CreateRoleRequest) {
		r.VersionType = v
	}
}

// WithWaitForActiveShards - sets the number of shard copies that must be active before proceeding with the CreateRole operation. defaults to 1, meaning the primary shard only. set to `all` for all shard copies, otherwise set to any non-negative value less than or equal to the total number of copies for the shard (number of replicas + 1).
func (f CreateRole) WithWaitForActiveShards(v string) func(*CreateRoleRequest) {
	return func(r *CreateRoleRequest) {
		r.WaitForActiveShards = v
	}
}

// WithPretty makes the response body pretty-printed.
func (f CreateRole) WithPretty() func(*CreateRoleRequest) {
	return func(r *CreateRoleRequest) {
		r.Pretty = true
	}
}

// WithHuman makes statistical values human-readable.
func (f CreateRole) WithHuman() func(*CreateRoleRequest) {
	return func(r *CreateRoleRequest) {
		r.Human = true
	}
}

// WithErrorTrace includes the stack trace for errors in the response body.
func (f CreateRole) WithErrorTrace() func(*CreateRoleRequest) {
	return func(r *CreateRoleRequest) {
		r.ErrorTrace = true
	}
}

// WithFilterPath filters the properties of the response body.
func (f CreateRole) WithFilterPath(v ...string) func(*CreateRoleRequest) {
	return func(r *CreateRoleRequest) {
		r.FilterPath = v
	}
}

// WithHeader adds the headers to the HTTP request.
func (f CreateRole) WithHeader(h map[string]string) func(*CreateRoleRequest) {
	return func(r *CreateRoleRequest) {
		if r.Header == nil {
			r.Header = make(http.Header)
		}
		for k, v := range h {
			r.Header.Add(k, v)
		}
	}
}

// WithOpaqueID adds the X-Opaque-Id header to the HTTP request.
func (f CreateRole) WithOpaqueID(s string) func(*CreateRoleRequest) {
	return func(r *CreateRoleRequest) {
		if r.Header == nil {
			r.Header = make(http.Header)
		}
		r.Header.Set("X-Opaque-Id", s)
	}
}
